import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;


public class TestRecognize {
    public static void main(String[] args) {
        try {
            // API endpoint
            String apiUrl = "http://172.27.130.255:10000/recognize/";

            // Path to the image file
            String imagePath = "C:/Users/17805/Desktop/insects/7.jpg";


            // Prepare JSON payload
            JSONObject json = new JSONObject();
            json.put("image_path", imagePath);

            // Send the request and get the response
            String response = sendPostRequest(apiUrl, json.toString());

            // Print the response from the API
            Gson gson = new Gson();
            JSONObject jsonObject = gson.fromJson(response, JSONObject.class);
            String result = (String) jsonObject.get("result");
            System.out.println("result: " + result.strip());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String sendPostRequest(String apiUrl, String jsonPayload) throws IOException, InterruptedException {
        // Create an HttpClient instance
        HttpClient client = HttpClient.newHttpClient();

        // Build the HttpRequest with JSON body
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(apiUrl))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
                .build();

        // Send the request and get the response
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // Return the response body (JSON response from FastAPI)
        return response.body();
    }
}
